/*
 * TltFrame.cpp
 *
 * Copyright 2012 Pieter Agten
 *
 * This file is part of tltgen.
 *
 * tltgen is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * tltgen is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with tltgen.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * @file   TltFrame.cpp
 * @author Pieter Agten (pieter.agten@gmail.com)
 * @date   3 sep 2012
 * @brief  The entry point of the Tltgen GUI.
 */

#include <wx/config.h>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/codecvt_null.hpp>
#include <boost/math/special_functions/nonfinite_num_facets.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <boost/make_shared.hpp>
#include <stdexcept>
#include <iostream>
#include <fstream>

#include "CelsiusScale.hpp"
#include "FahrenheitScale.hpp"
#include "KelvinScale.hpp"
#include "NewTableDialog.hpp"
#include "RepRapExportDialog.hpp"
#include "SaveFile.hpp"
#include "CsvThermistorTableWriter.hpp"
#include "MpfitLeastSquaresSolver.hpp"
#include "BetaModel.hpp"
#include "NormalizedSteinhartHartModel.hpp"
#include "LinearInterpolationModel.hpp"
#include "CachedThermistorModel.hpp"
#include "ResistanceTemperaturePlot.hpp"
#include "AdcValueTemperaturePlot.hpp"
#include "PowerTemperaturePlot.hpp"
#include "CsvImportDialog.hpp"

#include "TltFrame.hpp"

using boost::shared_ptr;
using boost::weak_ptr;
using boost::make_shared;

namespace tltgen {

  BEGIN_EVENT_TABLE(TltFrame, wxFrame)
  EVT_MENU(ID_NewTable, TltFrame::OnNewTable)
  EVT_MENU(ID_Open, TltFrame::OnOpen)
  EVT_MENU(ID_SaveAs, TltFrame::OnSaveAs)
  EVT_MENU(ID_ImportCsv, TltFrame::OnImportCsv)
  EVT_MENU(ID_ExportRepRap, TltFrame::OnExportRepRap)
  EVT_MENU(ID_ExportCsv, TltFrame::OnExportCsv)
  EVT_MENU(ID_About, TltFrame::OnAbout)
  EVT_MENU(ID_Quit,  TltFrame::OnQuit)
  EVT_MENU(ID_TemperatureScaleCelsius, TltFrame::OnTemperatureScaleCelsius)
  EVT_MENU(ID_TemperatureScaleFahrenheit, TltFrame::OnTemperatureScaleFahrenheit)
  EVT_MENU(ID_TemperatureScaleKelvin, TltFrame::OnTemperatureScaleKelvin)
  EVT_AUINOTEBOOK_PAGE_CHANGED(ID_Notebook, TltFrame::OnPageChanged)
  EVT_AUINOTEBOOK_PAGE_CLOSED(ID_Notebook, TltFrame::OnPageClosed)
  EVT_CLOSE(TltFrame::OnClose)
  END_EVENT_TABLE()

  TltFrame::TltFrame(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size) :
  wxFrame(parent, id, _("Tltgen"), pos, size),
    defaultLocale(std::locale::classic (), new boost::archive::codecvt_null<char>),
    solver(new MpfitLeastSquaresSolver())
  {
    this->fileMenu = new wxMenu();
    this->fileMenu->Append(ID_NewTable, _("New &table"));
    this->fileMenu->Append(ID_Open, _("&Open..."));
    this->fileMenu->Append(ID_SaveAs, _("&Save as..."));
    this->fileMenu->Enable(ID_SaveAs, false);

    wxMenu* importMenu = new wxMenu();
    importMenu->Append(ID_ImportCsv, _("CSV file..."));
    importMenu->Enable(ID_ImportCsv, true);
    this->fileMenu->AppendSubMenu(importMenu, _("&Import"));

    wxMenu* exportMenu = new wxMenu();
    exportMenu->Append(ID_ExportCsv, _("CSV file..."));
    exportMenu->Enable(ID_ExportCsv, false);
    exportMenu->Append(ID_ExportRepRap, _("RepRap firmware..."));
    exportMenu->Enable(ID_ExportRepRap, false);
    this->fileMenu->AppendSubMenu(exportMenu, _("&Export"));

    this->fileMenu->AppendSeparator();
    this->fileMenu->Append(ID_Quit, _("E&xit"));

    this->temperatureScaleMenu = new wxMenu();
    this->temperatureScaleMenu->AppendCheckItem(ID_TemperatureScaleCelsius, _("&Celsius"));
    this->temperatureScaleMenu->AppendCheckItem(ID_TemperatureScaleFahrenheit, _("&Fahrenheit"));
    this->temperatureScaleMenu->AppendCheckItem(ID_TemperatureScaleKelvin, _("&Kelvin"));

    wxMenu* helpMenu = new wxMenu();
    helpMenu->Append(ID_About, _("&About..."));

    wxMenuBar* menuBar = new wxMenuBar();
    menuBar->Append(this->fileMenu, _("&File"));
    menuBar->Append(temperatureScaleMenu, _("&Temperature scale"));
    menuBar->Append(helpMenu, _("&Help"));
    SetMenuBar(menuBar);

    this->notebook = new wxAuiNotebook(this, ID_Notebook, wxDefaultPosition, wxDefaultSize);
  
    createThermistorModels();
    CreateStatusBar();

    wxConfig config(wxString::FromUTF8("tltgen"), wxEmptyString, wxEmptyString, wxEmptyString, wxCONFIG_USE_LOCAL_FILE);
    TemperatureScaleSetting temperatureScaleSetting = 
      (TemperatureScaleSetting)config.Read(wxString::FromUTF8("TemperatureScale"), (long)TemperatureScaleCelsius);
    setTemperatureScaleSetting(temperatureScaleSetting, false);
  }

  void TltFrame::createThermistorModels()
  {
    shared_ptr<ThermistorModel> betaModel = make_shared<BetaModel>();
    shared_ptr<ThermistorModel> shhModel = make_shared<NormalizedSteinhartHartModel>();
    shared_ptr<ThermistorModel> linearInterpolationModel = make_shared<LinearInterpolationModel>();
    shared_ptr<ThermistorModel> cachedBetaModel = make_shared<CachedThermistorModel>(betaModel, 31);
    shared_ptr<ThermistorModel> cachedShhModel = make_shared<CachedThermistorModel>(shhModel, 31);
    shared_ptr<ThermistorModel> cachedLinearInterpolationModel = make_shared<CachedThermistorModel>(linearInterpolationModel, 31);
    this->thermistorModels.push_back(cachedBetaModel);
    this->thermistorModels.push_back(cachedShhModel);
    this->thermistorModels.push_back(cachedLinearInterpolationModel);
  }

  void TltFrame::OnClose(wxCloseEvent& WXUNUSED(event))
  {
    wxConfig config(wxString::FromUTF8("tltgen"), wxEmptyString, wxEmptyString, wxEmptyString, wxCONFIG_USE_LOCAL_FILE);
    config.Write(wxString::FromUTF8("TemperatureScale"), (long)getTemperatureScaleSetting());
    Destroy();
  }

  void TltFrame::OnPageChanged(wxAuiNotebookEvent& WXUNUSED(event))
  {
    UpdateEnabledMenuOptions();
  }

  void TltFrame::OnPageClosed(wxAuiNotebookEvent& event)
  {
    if (this->notebook->GetPageCount() == 0) {
      OnPageChanged(event);
    }
  }

  void TltFrame::UpdateEnabledMenuOptions()
  {
    bool panelActive = GetActiveTablePanel() != NULL;
    this->fileMenu->Enable(ID_ExportCsv, panelActive);
    this->fileMenu->Enable(ID_ExportRepRap, panelActive);
    this->fileMenu->Enable(ID_SaveAs, panelActive);
  }

  void TltFrame::OnNewTable(wxCommandEvent& WXUNUSED(event))
  {
    NewTableDialog newTableDialog(this, wxID_ANY, getTemperatureScale());
    if (hasActiveTablePanel()) {
      shared_ptr<ThermistorTable> thermistorTable =  ((TablePanel *)GetActiveTablePanel())->getThermistorTable();
      for (std::vector<shared_ptr<ThermistorModel> >::const_iterator it = this->thermistorModels.begin(); it != this->thermistorModels.end(); ++it) {
	shared_ptr<Thermistor> thermistor = (*it)->generate(thermistorTable, *getLeastSquaresSolver());
	newTableDialog.setThermistorValues(thermistor);
      }
      if (thermistorTable->hasAnalogToDigitalConverter()) {	
	newTableDialog.setAdcValues(thermistorTable->getAnalogToDigitalConverter());
      }
      if (thermistorTable->hasCircuit()) {
	newTableDialog.setCircuitValues(thermistorTable->getCircuit());
      }
    }

    if (newTableDialog.ShowModal() == wxID_OK) {
      try {
	shared_ptr<ThermistorTable> thermistorTable = newTableDialog.createThermistorTable();
	addTablePanel(thermistorTable);
	SetStatusText(_("New table created"));
      } catch (std::invalid_argument& ia) {
	SetStatusText(wxString::FromUTF8("Exception occurred while creating new table: ") + wxString::FromUTF8(ia.what()));
      }
    }
  }

  void TltFrame::OnOpen(wxCommandEvent& WXUNUSED(event))
  {
    wxFileDialog openFileDialog(this, _("Open Table"), wxEmptyString, 
				wxEmptyString, _("tltgen files (*.tlt)|*.tlt"), wxFD_OPEN|wxFD_FILE_MUST_EXIST);

    if (openFileDialog.ShowModal() == wxID_OK) {
      std::string filename = std::string(openFileDialog.GetPath().mb_str());
      std::locale inLocale(this->defaultLocale, new boost::math::nonfinite_num_get<char>);
      std::ifstream ifs(filename.c_str());
      ifs.imbue(inLocale);
      boost::archive::text_iarchive inputArchive(ifs, boost::archive::no_codecvt);

      try {
	SaveFile saveFile;
	inputArchive >> saveFile; 

	addTablePanel(saveFile.getThermistorTable());
	SetStatusText( _("File loaded successfully") );
      } catch (const std::exception& ex) {
	SetStatusText(wxString::FromUTF8("Error loading file: ") + wxString::FromUTF8(ex.what()));
      } catch (...) {
	SetStatusText(wxString::FromUTF8("Unknown error loading file."));
      }
    }
  }

  void TltFrame::addTablePanel(const shared_ptr<ThermistorTable>& thermistorTable)
  {
    int frameId = this->notebook->GetPageCount() + 1;
    wxString title = wxString::Format(_("Table %d"), frameId);

    TablePanel *tablePanel = new TablePanel(this->notebook, frameId, thermistorTable, getLeastSquaresSolver(), getTemperatureScale(), wxDefaultPosition, wxDefaultSize);
    shared_ptr<ResistanceTemperaturePlot> resistancePlot = make_shared<ResistanceTemperaturePlot>(thermistorTable, getLeastSquaresSolver(), getTemperatureScale());
    weak_ptr<TemperaturePlot> wkResistancePlot(resistancePlot);
    this->temperaturePlots.push_back(wkResistancePlot);

    shared_ptr<AdcValueTemperaturePlot> adcValuePlot = make_shared<AdcValueTemperaturePlot>(thermistorTable, getLeastSquaresSolver(), getTemperatureScale());
    weak_ptr<TemperaturePlot> wkAdcValuePlot(adcValuePlot);
    this->temperaturePlots.push_back(wkAdcValuePlot);

    shared_ptr<PowerTemperaturePlot> powerPlot = make_shared<PowerTemperaturePlot>(thermistorTable, getLeastSquaresSolver(), getTemperatureScale());
    weak_ptr<TemperaturePlot> wkPowerPlot(powerPlot);
    this->temperaturePlots.push_back(wkPowerPlot);

    for (std::vector<shared_ptr<ThermistorModel> >::const_iterator it = this->thermistorModels.begin(); it != this->thermistorModels.end(); ++it) {
      tablePanel->addThermistorModel(*it);
      resistancePlot->addThermistorModel(*it);
      adcValuePlot->addThermistorModel(*it);
      powerPlot->addThermistorModel(*it);
    }
    tablePanel->addPlot(resistancePlot);
    tablePanel->addPlot(adcValuePlot);
    tablePanel->addPlot(powerPlot);
    this->notebook->AddPage(tablePanel, title, true);
  }

  void TltFrame::OnSaveAs(wxCommandEvent& WXUNUSED(event))
  {
    wxFileDialog saveFileDialog(this, _("Save Table as"), wxEmptyString, 
				wxEmptyString, _("tltgen files (*.tlt)|*.tlt"), wxFD_SAVE|wxFD_OVERWRITE_PROMPT);

    if (saveFileDialog.ShowModal() == wxID_OK) {
      TablePanel *currentTablePanel = ((TablePanel *)GetActiveTablePanel());
      SaveFile saveFile(currentTablePanel->getThermistorTable());

      std::string filename = std::string(saveFileDialog.GetPath().mb_str());
      std::locale outLocale(this->defaultLocale, new boost::math::nonfinite_num_put<char>);
      std::ofstream ofs(filename.c_str());
      ofs.imbue(outLocale);
      boost::archive::text_oarchive outputArchive(ofs, boost::archive::no_codecvt);      

      try {
	outputArchive << saveFile;
	SetStatusText( _("Table saved successfully") );
      } catch (const std::exception& ex) {
	SetStatusText(wxString::FromUTF8("Error saving file: ") + wxString::FromUTF8(ex.what()));
      } catch (...) {
	SetStatusText(wxString::FromUTF8("Unknown error while saving file"));
      }
    }
  }

  bool TltFrame::hasActiveTablePanel() const
  {
    return this->notebook->GetPageCount() > 0;
  }

  TablePanel *TltFrame::GetActiveTablePanel() const
  {
    return (TablePanel *)this->notebook->GetPage(this->notebook->GetSelection());
  }

  void TltFrame::OnImportCsv(wxCommandEvent& WXUNUSED(event))
  {
    CsvImportDialog csvImportDialog(this, wxID_ANY);

    if (csvImportDialog.ShowModal() == wxID_OK) {
      try {
	shared_ptr<ThermistorTable> thermistorTable = csvImportDialog.createThermistorTable();
	if (thermistorTable.get() != NULL) {
	  addTablePanel(thermistorTable);
	  SetStatusText( _("CSV file imported successfully") );
	}
      } catch (const std::exception& ex) {
	SetStatusText(wxString::FromUTF8("Error importing CSV file: ") + wxString::FromUTF8(ex.what()));
      } catch (...) {
	SetStatusText(wxString::FromUTF8("Unknown error importing CSV file."));
      }
    }
  }

  void TltFrame::OnExportCsv(wxCommandEvent& WXUNUSED(event))
  {
    wxFileDialog saveFileDialog(this, _("Export CSV file"), wxEmptyString, 
				  wxEmptyString, _("CSV files (*.csv)|*.csv"), wxFD_SAVE|wxFD_OVERWRITE_PROMPT);

    if (saveFileDialog.ShowModal() == wxID_OK) {
      TablePanel *currentTablePanel = ((TablePanel *)GetActiveTablePanel());
      
      CsvThermistorTableWriter writer;
      
      std::string filename = std::string(saveFileDialog.GetPath().mb_str());
      std::ofstream outputFile;
      try {
	outputFile.open(filename.c_str(), std::ios_base::out);
	writer.write(outputFile, currentTablePanel->getThermistorTable());
	outputFile.close();
	SetStatusText( _("CSV file exported successfully") );
      } catch (const std::exception& ex) {
	SetStatusText(wxString::FromUTF8("Error exporting to CSV file: ") + wxString::FromUTF8(ex.what()));
      } catch (...) {
	SetStatusText(wxString::FromUTF8("Unknown error while exporting to CSV file"));
      }
    }
  }

  void TltFrame::OnExportRepRap(wxCommandEvent& WXUNUSED(event))
  {
    TablePanel *currentTablePanel = ((TablePanel *)GetActiveTablePanel());
    RepRapExportDialog repRapExportDialog(this, wxID_ANY, currentTablePanel->getThermistorTable());
    if (repRapExportDialog.ShowModal() == wxID_OK) {
      SetStatusText( _("File exported successfully") );
    }
  }

  void TltFrame::setTemperatureScaleSetting(TemperatureScaleSetting temperatureScaleSetting, bool showMessage)
  {
    try {
      this->temperatureScaleMenu->Check(ID_TemperatureScaleCelsius, false);
      this->temperatureScaleMenu->Check(ID_TemperatureScaleFahrenheit, false);
      this->temperatureScaleMenu->Check(ID_TemperatureScaleKelvin, false);

      switch (temperatureScaleSetting) {
      case TemperatureScaleCelsius:
	setTemperatureScale(boost::make_shared<CelsiusScale>());
	this->temperatureScaleMenu->Check(ID_TemperatureScaleCelsius, true);
	break;
      case TemperatureScaleFahrenheit:
	setTemperatureScale(boost::make_shared<FahrenheitScale>());
	this->temperatureScaleMenu->Check(ID_TemperatureScaleFahrenheit, true);
	break;
      case TemperatureScaleKelvin:
	setTemperatureScale(boost::make_shared<KelvinScale>());
	this->temperatureScaleMenu->Check(ID_TemperatureScaleKelvin, true);
	break;
      }
      if (showMessage) {
	SetStatusText(wxString::FromUTF8("Set temperature scale to ") + wxString::FromUTF8(getTemperatureScale()->getName().c_str()));
      }
    } catch (std::exception& e) {
      SetStatusText(wxString::FromUTF8("Exception while setting temperature scale: ") + wxString::FromUTF8(e.what()));
    }
  }

  TltFrame::TemperatureScaleSetting TltFrame::getTemperatureScaleSetting() const
  {
    if (this->temperatureScaleMenu->IsChecked(ID_TemperatureScaleCelsius)) {
      return TemperatureScaleCelsius;
    } else if (this->temperatureScaleMenu->IsChecked(ID_TemperatureScaleFahrenheit)) {
      return TemperatureScaleFahrenheit;
    } else if (this->temperatureScaleMenu->IsChecked(ID_TemperatureScaleKelvin)) {
      return TemperatureScaleKelvin;
    } else {
      std::cerr << "No temperature scale selected!" << std::endl;
      throw std::runtime_error("No temperature scale selected!");
    }
  }

  void TltFrame::OnTemperatureScaleCelsius(wxCommandEvent& WXUNUSED(event))
  {
    setTemperatureScaleSetting(TltFrame::TemperatureScaleCelsius, true);
  }
  void TltFrame::OnTemperatureScaleFahrenheit(wxCommandEvent& WXUNUSED(event))
  {
    setTemperatureScaleSetting(TltFrame::TemperatureScaleFahrenheit, true);
  }
  void TltFrame::OnTemperatureScaleKelvin(wxCommandEvent& WXUNUSED(event))
  {
    setTemperatureScaleSetting(TltFrame::TemperatureScaleKelvin, true);
  }

  void TltFrame::setTemperatureScale(const boost::shared_ptr<TemperatureScale>& temperatureScale)
  {  
    this->temperatureScale = temperatureScale;
    
    for (size_t i = 0; i < this->notebook->GetPageCount(); ++i) {
      TablePanel *tablePanel = (TablePanel*)this->notebook->GetPage(i);
      tablePanel->setTemperatureScale(temperatureScale);
    }
    
    std::list<weak_ptr<TemperaturePlot> >::iterator it = this->temperaturePlots.begin();
    while (it != this->temperaturePlots.end()) {
      if ((*it).expired()) {
	it = this->temperaturePlots.erase(it);
      } else {
	(*it).lock()->setTemperatureScale(temperatureScale);
	++it;
      }
    }
  }
  shared_ptr<TemperatureScale> TltFrame::getTemperatureScale() const
  {
    return this->temperatureScale;
  }

  shared_ptr<LeastSquaresSolver> TltFrame::getLeastSquaresSolver() const
  {
    return this->solver;
  }

  void TltFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
  {
    wxMessageBox( _("Created by Pieter Agten <pieter.agten@gmail.com>"),
		  _("About Tltgen"),
		  wxOK | wxICON_INFORMATION, this );
  }

  void TltFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
  {
    Close(true);
  }

}


